package com.qianniu.napi.admin.service.akka;

import akka.actor.UntypedActor;
import com.qianniu.napi.admin.entity.Goods;
import com.qianniu.napi.admin.service.IGoodsService;
import com.qianniu.napi.admin.service.IRedisService;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GoodsActor extends UntypedActor {

    private final static Logger logger = LoggerFactory.getLogger(GoodsActor.class);

    private IRedisService redisService = (IRedisService) SpringUtil.getBean("redisServiceImpl");
    private IGoodsService goodsService = (IGoodsService) SpringUtil.getBean("goodsServiceImpl");

    @Override
    public void onReceive(Object message) {
        logger.info(">>>>>>OrderActor in");

        if (message instanceof String) {
            String msg = message.toString();
            logger.info(">>>>>>GoodsActor receive message:" + msg);
            try {
                // 格式 type+uid+toke
                String[] arr = msg.split("@");
                logger.info(">>>>>>receive arr.length=" + arr.length);
//            if (arr.length < 3) return;

                String type = arr[0];
                String yw1 = arr[1];
                String yw2 = arr.length >= 3 ? arr[2] : "";
                String yw3 = arr.length >= 4 ? arr[3] : "";
                logger.info(">>>>>>receive type:" + type);
                logger.info(">>>>>>receive yw1:" + yw1);
                logger.info(">>>>>>receive yw2:" + yw2);

                switch (type) {
                    case Constants.AKKA_MSG_GOODS_VIEW:
                        logger.info(">>>>>>switch here[AKKA_MSG_GOODS_VIEW]");
                        viewGoods(yw1);
                        break;
                    case Constants.AKKA_MSG_ORDER_HEXIAO:
                        logger.info(">>>>>>switch here[AKKA_MSG_ORDER_HEXIAO]");
                        updateGoodsStore(yw1);
                        break;
                    default:
                        return;
                }
            } catch (Exception e) {
                logger.error(">>>>>>OrderActor process error", e);
            }
        }
    }

    private void viewGoods(String gid) {
        Goods goods = goodsService.selectById(gid);
        if (goods == null) return;
        Goods gd = new Goods();
        gd.setId(Long.valueOf(gid));
        gd.setViews(goods.getViews()==null?1:goods.getViews() + 1);
        gd.updateById();
    }

    private void updateGoodsStore(String gid) {
        Goods goods = goodsService.selectById(gid);
        if (goods == null) return;
        Goods gd = new Goods();
        gd.setId(Long.valueOf(gid));
        gd.setViews(goods.getViews() + 1);
        gd.updateById();
    }

}
